﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

namespace NWBA_Public
{
    public partial class ATM : System.Web.UI.Page
    {
        private static List<Account> myAcct;
        protected void Page_Load(object sender, EventArgs e)
        {
            //see weather the user has logged in or not
            if ((string)(Session["userName"]) == null)
            {
                //if not logged in direct him to login.aspx
                Response.Redirect("Login.aspx", true);
            }
            Customer cust = Session["Customer"] as Customer;
            //retrieve all the account that associate with this user
            myAcct = AccountRepostiory.Select(cust);
            //associate all the accounts to the dropdownlist for user to select it.
            if (DropDownList2.Items.Count <= myAcct.Count)
            {
                foreach (Account acct in myAcct)
                {
                    DropDownList2.Items.Add(acct.AccountNumber.ToString());
                }
            }
        }
        // to set the visibility of the transfered account.
        protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
        {

            if (DropDownList1.SelectedValue == "Transfer")
            {
                ToAcctLabel.Visible = true;
                ToAcctTB.Visible = true;
            }
            else
            {
                ToAcctLabel.Visible = false;
                ToAcctTB.Visible = false;
            }
        }
        // TO check how many accounts that user selected.
        protected Account selectAccount()
        {
            var acctID = from id in myAcct
                         where id.AccountNumber.Equals(int.Parse(DropDownList2.SelectedItem.Value))
                         select id;
            if (acctID.Count() > 1)
            {
                return null;
            }
            foreach (Account acct in acctID)
            {
                return acct;
            }
            return null;
        }
        protected void ExcuteB_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                if (DropDownList1.SelectedValue == "Deposite")
                {
                    //get the account that user currently selected, make sure he/she doesn't select the "select account" value in the drop list
                    Account acct = selectAccount();
                    //insert the new transaction to the databse and return a true or false value.
                    if (acct != null)
                    {
                        // set up a new transaction
                        Transaction newTrans = new Transaction('D', acct.AccountNumber, acct.AccountNumber, decimal.Parse(AmountTB.Text), CommentArea.Value, DateTime.Now);
                        //insert the new row into transaction table as well as the service transactions if applies
                        if (TransactionRepository.Insert(newTrans) && TransactionRepository.ServiceFee(acct, CommentArea.Value, true))
                        {
                            if (AccountRepostiory.UpdateDeposite(acct, decimal.Parse(AmountTB.Text.ToString())))
                            {
                                Response.Redirect("TransactionStatue.aspx", true);
                            }
                            else
                            {
                                Response.Write("Not good");
                            }
                        }
                    }
                }
                else if (DropDownList1.SelectedValue == "Withdraw")
                {
                    // get the acount to be withdraw from the drop down box
                    Account acct = selectAccount();
                    if (acct != null)
                    {
                        //set a new transaction
                        Transaction newTrans = new Transaction('W', acct.AccountNumber, acct.AccountNumber, decimal.Parse(AmountTB.Text), CommentArea.Value, DateTime.Now);
                        if (TransactionRepository.Insert(newTrans) && TransactionRepository.ServiceFee(acct, CommentArea.Value, true))
                        {
                            if (AccountRepostiory.UpdateWithdraw(acct, decimal.Parse(AmountTB.Text.ToString())))
                            {
                                Response.Redirect("TransactionStatue.aspx", true);
                            }
                            else
                            {
                                Label Indicator = new Label();
                                Indicator.Text = "Not enough fund left";
                                PlaceHolder1.Controls.Add(Indicator);
                            }
                        }
                        else
                        {
                            Response.Write("Not good");
                        }
                    }

                }
                else if (DropDownList1.SelectedValue == "Transfer")
                {
                    Account acct = selectAccount();
                    Account toAcct = AccountRepostiory.SelectSingleAccount(int.Parse(ToAcctTB.Text));
                    if (acct != null)
                    {
                        if (acct.AccountNumber != toAcct.AccountNumber)
                        {
                            Transaction newTrans = new Transaction('T', acct.AccountNumber, toAcct.AccountNumber, decimal.Parse(AmountTB.Text), CommentArea.Value, DateTime.Now);
                            if (TransactionRepository.Insert(newTrans) && TransactionRepository.ServiceFee(acct, CommentArea.Value, true))
                            {
                                if (AccountRepostiory.UpdateTransfer(acct, toAcct, decimal.Parse(AmountTB.Text)))
                                {
                                    Response.Redirect("TransactionStatue.aspx", true);
                                }
                                else
                                {
                                    Label Indicator = new Label();
                                    Indicator.Text = "Not enough fund (please note that at least $0 in saving account or at least $200 in checking account";
                                    PlaceHolder1.Controls.Add(Indicator);
                                }
                            }
                        }
                        else
                        {
                            Response.Write("Can't ransfer money between same account");
                        }
                    }
                }
            }
        }

        protected void ToAcctTB_TextChanged(object sender, EventArgs e)
        {
            try
            {
                Account targetAcct = AccountRepostiory.SelectSingleAccount(int.Parse(ToAcctTB.Text));
                if (targetAcct != null)
                {
                    Label Indicator = new Label();
                    Indicator.Text = "Ok";
                    PlaceHolder1.Controls.Add(Indicator);
                }
                else
                {
                    //tell the user that the acocunt he/she want to transfer doesn't exist in the bank system
                    Label Indicator = new Label();
                    Indicator.Text = "Account Not Exist";
                    PlaceHolder1.Controls.Add(Indicator);
                }
            }
            catch (Exception ne)
            {
                Label Indicator = new Label();
                Indicator.Text = "Please enter number only";
                PlaceHolder1.Controls.Add(Indicator);
            }
        }

        protected void TransTypeValidator_ServerValidate(object source, ServerValidateEventArgs args)
        {
            if (DropDownList1.SelectedValue == "Select an Account Type")
            {
                args.IsValid = false;
            }
        }

        protected void AcctValidator_ServerValidate(object source, ServerValidateEventArgs args)
        {
            if (DropDownList2.SelectedValue == "Select Account")
            {
                args.IsValid = false;
            }
        }

        protected void CancellB_Click(object sender, EventArgs e)
        {
            //reset the amount to null
            AmountTB.Text = "";            
        }
    }
}